<?php
/**
 * @author Voislav Jovanovic <voislavj@gmail.com>
 * main entry point for the framework
 */

class View{
	
	public $layout = "layout";
	
	public $_vars = array();
	public $locales;
	
	public static $inst;
	
	public function __construct() {
		self::_loadLocales();
	}
	
	public static function _getInstance() {
		if(!self::$inst) {
			self::$inst = new View();
		}
		return self::$inst;
	}
	
	private function _loadLocales() {
		// load locales
		$lang = $_SESSION["language"];
		$path = "resource/locale/$lang.lang";
		if(file_exists($path)) {
			$this->locales = array();
			foreach(file($path) as $line) {
				list($key, $val) = explode("=", $line, 2);
				$key = trim($key); 
				$val = trim($val);
				$this->locales[$key] = $val;
			}
		}
	}
	
	public function render($view=false, $additional_vars) {
		$prev = ob_get_contents();
		ob_clean();
		
		if(!$view){
			$view = "{$this->request->controller}/{$this->request->action}";
		}
		
		foreach($additional_vars as $k=>$v){
			$this->set($k, $v);
		}
		
		$this->set("__content", $this->fetch($view));
		echo $prev;
		echo $this->_fetch("layout");
	}
	
	public function renderError($type, $vars){
		$this->render("errors/$type", $vars);
	}
	
	public function fetch($path=null) {
		$prev = ob_get_contents();
		ob_clean();
		if(!$path){
			$path = "{$this->request->controller}/{$this->request->action}";
		}
		return $this->_fetch($path);
	}
	
	public function _fetch($path) {
		$path = DIR_ROOT . "app/views/$path.ctp";
		foreach($this->_vars as $k=>$v) {
			$$k = $v;
		}
		if(file_exists($path)) {
			include_once $path;
		}else{
			throw new Exception("View not found ($path)");
		}
		$ret = ob_get_contents();
		ob_clean();
		return $ret;
	}
	
	public function set($name, $value) {
		$this->_vars[$name] = $value;
	}
	
	public static function translate($text) {
		$V = self::_getInstance();
		$ret = $text;
		
		$V->_loadLocales();
		if(isset($V->locales[$text])) {
			$ret = $V->locales[$text];
		}
		return $ret;
	}
}